<?php

namespace IDock\Insurance\ZYIC\Request;

use Exception;
use IDock\Insurance\ZYIC\Request\AllZYICRequest;
use IDock\Insurance\ZYIC\Response\NonCarInquiryResponse;
use IDock\Insurance\ZYIC\Response\NonCarUnderwritingResponse;
use IDock\Insurance\ZYIC\ZYICEnums;
use IDock\Visitor\NonCar\NonCarProductListVisitor;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

class NonCarUnderwritingRequest extends AllZYICRequest
{

    protected $urlTip = '非车核保';

    public $serviceName = 'augeas.car.underwriting';

    protected $response = NonCarUnderwritingResponse::class;

    /*** @var  PremiumInquiryVisitor $visitor */
    protected $visitor;

    public $channelCode;

    public $proposalNo = '';

    public function generate(): array
    {
        /*** @var NonCarProductVisitor $plan */
        $plan = $this->visitor->getNonCarUnderwritingVisitor()->getNonCarList()[0] ?? [];
        $arr = [
            'channelCode' => $this->channelCode,
            'channelOrderNo' => $this->visitor->getExtInfoVisitor()->argc['channelOrderNo'] ?? '',
            'applyTime' => date('YmdHis'),
            'effectiveTime' => date('YmdHis', strtotime($this->visitor->biStartData ?: $this->visitor->ciStartData)),
            'expireTime' => date('YmdHis', strtotime($this->visitor->biEndData ?: $this->visitor->ciEndData)),
            'planCode' => $plan->planCode,
            'insuredList' => $this->getInsuredList(),
        ];
        if($this->visitor->getApplicantVisitor()->typeCode == 'R1'){
            $arr['personHolder'] = $this->getHolder();
        }else{
            $arr['orgHolder'] = $this->getOrgHolder();
        }
        return $arr;
    }

    private function getHolder()
    {
        $arr = [
            'birthday' => $this->getBirthday($this->visitor->getApplicantVisitor()->certificateNo),
            'certNo' => $this->visitor->getApplicantVisitor()->certificateNo,
            'certType' => ZYICEnums::$nonCarCertificateTypeCode[$this->visitor->getApplicantVisitor()->certificateTypeCode] ?? '',
            'certExpiryDate' => $this->visitor->getApplicantVisitor()->certificateEndDate ? date('Ymd',strtotime($this->visitor->getApplicantVisitor()->certificateEndDate)) : '',
            'abroadType' => '1',//境内
            'gender' => $this->getGenderByIDcard($this->visitor->getApplicantVisitor()->certificateNo),
            'phone' => $this->visitor->getApplicantVisitor()->mobile,
            'name' => $this->visitor->getApplicantVisitor()->name,
            'email' => $this->visitor->getApplicantVisitor()->email,
            'homeAddress' => [
                'address' => $this->visitor->getApplicantVisitor()->address,
                'districtCode' => $this->visitor->getApplicantVisitor()->areaCode,
                'cityCode' => $this->visitor->getApplicantVisitor()->cityCode,
                'provinceCode' => $this->visitor->getApplicantVisitor()->provinceCode,
            ],
        ];
        return $arr;
    }

    private function getOrgHolder()
    {
        $arr = [
            'name' => $this->visitor->getApplicantVisitor()->name,
            'certNo' => $this->visitor->getApplicantVisitor()->certificateNo,
            'certType' => ZYICEnums::$nonCarCertificateTypeCode[$this->visitor->getApplicantVisitor()->certificateTypeCode] ?? '',
            'certEffectiveDate' => $this->visitor->getApplicantVisitor()->certificateStartDate ? date('Ymd',strtotime($this->visitor->getApplicantVisitor()->certificateStartDate)) : '',
            'certExpiryDate: ' => $this->visitor->getApplicantVisitor()->certificateEndDate ? date('Ymd',strtotime($this->visitor->getApplicantVisitor()->certificateEndDate)) : '',
            'contractCertNo' => $this->visitor->getApplicantVisitor()->linkManCertificateNo,//联系人证件号码
            'contractCertType' => ZYICEnums::$nonCarCertificateTypeCode[$this->visitor->getApplicantVisitor()->linkManCertificateTypeCode] ?? '',
            'phoneNo' => $this->visitor->getApplicantVisitor()->mobile,
            'contractName' => $this->visitor->getApplicantVisitor()->linkManName,
            'email' => $this->visitor->getApplicantVisitor()->email,
            'industry' => '99',//默认其他
            'contractHomeAddress' => [
                'address' => $this->visitor->getApplicantVisitor()->address,
                'districtCode' => $this->visitor->getApplicantVisitor()->areaCode,
                'cityCode' => $this->visitor->getApplicantVisitor()->cityCode,
                'provinceCode' => $this->visitor->getApplicantVisitor()->provinceCode,
            ],
        ];
        return $arr;
    }

    private function getInsuredList()
    {
        $insured = $this->visitor->getInsuredVisitor();
        $arr = [
            'name' => $insured->name,
            'certType' => ZYICEnums::$nonCarCertificateTypeCode[$insured->certificateTypeCode] ?? '',
            'certNo' => $insured->certificateNo,
            'gender' => $this->getGenderByIDcard($insured->certificateNo),
            'birthday' => $this->getBirthday($insured->certificateNo),
            'applyNum' => 1,//投保份数
            'insuredObjectList' => [
                [
                    'subjectInfoList' => [
                        [
                            'key' => 'FWDZ',
                            'value' => $this->getAddressJson(),
                        ],
                        ['key' => 'RQH']
                    ],
                    'subjectMatterEnum' => 'BD0002',//默认房屋 标的类型
                ]
            ],
            'relationToPH' => $insured->name == $this->visitor->getApplicantVisitor()->name ? '1' :'5',
            'additionalObjectList' => [
                [
                    'subjectInfoList' => $this->getVehicle(),
                    'subjectMatterEnum' => 'BF0001',//车辆：BF0001
                ]
            ],
        ];
        if($this->visitor->getApplicantVisitor()->typeCode != 'R1'){
            $arr['relationToPH'] = '5';//企业投保人只能选其他
        }
        return [$arr];
    }

    private function getAddressJson()
    {
        $insured = $this->visitor->getInsuredVisitor();
        $json = [
            'province' => [
                'code' => $insured->provinceCode,
                'name' => $insured->provinceName,
            ],
            'secondCity' => [
                'code' => $insured->cityCode,
                'name' => $insured->cityName,
            ],
            'city' => [
                'code' => $insured->areaCode,
                'name' => $insured->areaName,
            ],
            'detail' => $insured->address,
        ];
        return json_encode($json,320);
    }

    private function getVehicle()
    {
        $vehicle = [
            [
                'key' => 'CL001',
                'value' => $this->visitor->getVehicleVisitor()->licenseNo,
            ],
            [
                'key' => 'CL002',
                'value' => $this->visitor->getVehicleVisitor()->vin,
            ],
            [
                'key' => 'FDJHM',
                'value' => $this->visitor->getVehicleVisitor()->engineNo,
            ],
            [
                'key' => 'HDZK',
                'value' => $this->visitor->getVehicleVisitor()->vehicleSeat,
            ],
            [
                'key' => 'CLLX',
                'value' => $this->visitor->getVehicleVisitor()->useNatureCode == '02' ? '1' : '2',
            ],
            [
                'key' => 'CFLAG',
                'value' => intval($this->visitor->getVehicleVisitor()->isNewVehicle),
            ],
        ];
        return $vehicle;
    }

    private function getGenderByIDcard($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new \Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard, 16, 1)) % 2;
        return $gender ? 'M' : 'F';
    }

    private function getBirthday($idCard)
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        return substr($idCard, 6, 4) . substr($idCard, 10, 2) . substr($idCard, 12, 2);
    }
}
